package com.fenghongzhang.module_main.ui

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.fenghongzhang.lib_core.utils.Router
import com.fenghongzhang.module_main.R
import com.fenghongzhang.module_main.databinding.ActivityGuideV2Binding
import com.gyf.immersionbar.ktx.immersionBar
import com.jczy.cyclone.mmkv.AppMMKV
import kotlin.math.roundToInt

/**
 *@author Wcj
 *@description 引导页
 *@date 2022/7/14 16:22
 */
@Route(path = Router.Ui.GuideActivity)
class GuideActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityGuideV2Binding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView<ActivityGuideV2Binding>(this, R.layout.activity_guide_v2)
        showIndicator()
        immersionBar {
            this.statusBarDarkFont(true)
        }
        mBinding.vp.adapter = GuidePageAdapter()
        mBinding.vp.offscreenPageLimit = 1
        mBinding.vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                // mBinding.vIndicator.translationX = 48.dp * (positionOffset + position)
                when (position) {
                    0 -> {
                        mBinding.guide1.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_checked)
                        mBinding.guide2.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_uncheck)
                        mBinding.guide3.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_uncheck)
                    }
                    1 -> {
                        mBinding.guide1.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_uncheck)
                        mBinding.guide2.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_checked)
                        mBinding.guide3.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_uncheck)
                    }
                    2 -> {
                        mBinding.guide1.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_uncheck)
                        mBinding.guide2.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_uncheck)
                        mBinding.guide3.background = ContextCompat.getDrawable(this@GuideActivity, R.drawable.bg_indicator_checked)
                    }

                }
            }

            override fun onPageSelected(position: Int) {
                if (position == 2) {
                    hideIndicator()
                } else {
                    showIndicator()
                }
            }
        })

        //立即体验
        mBinding.btnEnter.setOnClickListener {
            AppMMKV.needGuide = false
            ARouter.getInstance()
                .build(Router.Ui.MainActivity)
                .withTransition(R.anim.right_in, R.anim.left_out)
                .navigation(this)
            ActivityCompat.finishAffinity(this)
        }

    }

    private inner class GuidePageAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val guidePicRes = listOf(R.mipmap.bg_guide_1, R.mipmap.bg_guide_2, R.mipmap.bg_guide_3)
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return object : RecyclerView.ViewHolder(ImageView(parent.context).apply {
                scaleType = ImageView.ScaleType.CENTER_CROP
                layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            }) {}
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            //按屏幕比例，截取上部分的图片
            scaleImage(holder.itemView, guidePicRes[position])

        }

        override fun getItemCount(): Int = guidePicRes.size

    }

    private fun hideIndicator() {
        mBinding.lGuide.visibility = View.INVISIBLE
        mBinding.btnEnter.visibility = View.VISIBLE
    }

    private fun showIndicator() {
        mBinding.lGuide.visibility = View.VISIBLE
        mBinding.btnEnter.visibility = View.INVISIBLE
    }

    fun scaleImage(view: View, drawableResId: Int) {
        // 获取屏幕的高宽
        val outSize = Point()
        window.windowManager.defaultDisplay.getSize(outSize)
        // 解析将要被处理的图片
        val resourceBitmap: Bitmap = BitmapFactory.decodeResource(resources, drawableResId) ?: return
        // 使用图片的缩放比例计算将要放大的图片的高度
        var bitmapScaledHeight = 0
        var bitmapScaledWidth = 0
        bitmapScaledHeight = (resourceBitmap.height * outSize.x * 1.0f / resourceBitmap.width).roundToInt()
        bitmapScaledWidth = outSize.x

        if (bitmapScaledHeight < outSize.y) {
            //已宽度为基准，缩放后图片高度小于屏幕高度,修改为以高度为基准
            bitmapScaledHeight = outSize.y
            bitmapScaledWidth = (resourceBitmap.width * outSize.y * 1.0f / resourceBitmap.height).roundToInt()
        }

        // 以屏幕的宽度为基准，如果图片的宽度比屏幕宽，则等比缩小，如果窄，则放大
        val scaledBitmap: Bitmap = Bitmap.createScaledBitmap(resourceBitmap, bitmapScaledWidth, bitmapScaledHeight, false)
        view.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                //这里防止图像的重复创建，避免申请不必要的内存空间
                if (scaledBitmap.isRecycled) //必须返回true
                    return true
                // 当UI绘制完毕，我们对图片进行处理
                val viewHeight = view.measuredHeight
                // 计算将要裁剪的图片的顶部以及底部的偏移量
                val offset: Int = (scaledBitmap.height - viewHeight) / 2
                // 对图片以中心进行裁剪，裁剪出的图片就是非常适合做引导页的图片了
                val finallyBitmap: Bitmap = if (scaledBitmap.height - offset * 2 < scaledBitmap.height) {
                    Bitmap.createBitmap(
                        scaledBitmap, 0, 0, scaledBitmap.width,
                        scaledBitmap.height - offset * 2
                    )
                } else {
                    Bitmap.createBitmap(
                        scaledBitmap, 0, 0, scaledBitmap.width,
                        scaledBitmap.height
                    )
                }


                if (finallyBitmap != scaledBitmap) { //如果返回的不是原图，则对原图进行回收
                    scaledBitmap.recycle()
                    System.gc()
                }
                // 设置图片显示
                (view as ImageView).setImageBitmap(finallyBitmap)
                return true
            }
        })
    }
}